package cn.lili.modules.grab.dingdong.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Author zlb
 * @Date 2021/4/26 13:52
 * @return
 **/
@Slf4j
public class HttpClientUtil {
    private static final String CHARSET = "UTF-8";
    private static final int MAX_RETRY = 3;
    private static HttpClientBuilder clientBuilder;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(50);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10 * 60 * 1000).setConnectTimeout(60 * 1000).setConnectionRequestTimeout(10 * 1000).build();
        clientBuilder = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig);
        clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(MAX_RETRY, true));
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    }

    public static HttpClient getHttpClient() {
        return clientBuilder.build();
    }
    
    /**
     * application/x-www-form-urlencoded 格式数据
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String post(String url, List<NameValuePair> params, Map<String, String> headers) throws UnsupportedEncodingException {
        String body = null;
        HttpPost post = new HttpPost(url);
        if (params != null) {
				post.setEntity(new UrlEncodedFormEntity(params, CHARSET));
        }
        //告诉WEB服务器自己接受什么介质类型,浏览器告诉服务器自己能接收的字符集。
        post.addHeader("Accept", "application/json; charset=UTF-8");
        //发送的内容类型
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                Header header = new BasicHeader(entry.getKey(), entry.getValue());
                post.addHeader(header);
            }
        }
        HttpClient client = getHttpClient();
        try {
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                body = EntityUtils.toString(entity);
               // EntityUtils.consume(entity);
            } else {
                log.error("response status error.status code:" + statusCode + ",url:" + url);
            }
        } catch (Exception e) {
            log.error("request error.request url:" + url, e);
        } finally {
            post.releaseConnection();
        }
        return body;
    }
    
    /**
     * application/json; charset=UTF-8 格式的数据
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static String post(String url, String params, Map<String, String> headers) {
        String body = null;
        HttpPost post = new HttpPost(url);
        if (StringUtils.isNotBlank(params)) {
           
				post.setEntity(new StringEntity(params, CHARSET));
        }
        //告诉WEB服务器自己接受什么介质类型,浏览器告诉服务器自己能接收的字符集。
        post.addHeader("Accept", "application/json; charset=UTF-8");
        //发送的内容类型
        post.addHeader("Content-Type", "application/json; charset=UTF-8");
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                Header header = new BasicHeader(entry.getKey(), entry.getValue());
                post.addHeader(header);
            }
        }
        HttpClient client = getHttpClient();
        try {
            HttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                body = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            } else {
                log.error("response status error.status code:" + statusCode + ",url:" + url);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("request error.request url:" + url, e);
        } finally {
            post.releaseConnection();
        }
        return body;
    }

    public static String post(String url) {
        return post(url, null);
    }

    public static String post(String url, String params) {
        return post(url, params, new HashMap<String, String>());
    }

    public static String post(String url, String params, String cookie) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Cookie", cookie);
        return post(url, params, headers);
    }

    public static String get(String url) {
        String body = null;
        HttpGet get = new HttpGet(url);
        //告诉WEB服务器自己接受什么介质类型,浏览器告诉服务器自己能接收的字符集。
        get.addHeader("Accept", "application/json; charset=UTF-8");
        HttpClient client = getHttpClient();
        try {
            HttpResponse response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                body = EntityUtils.toString(entity);
                System.out.println(body);
                EntityUtils.consume(entity);
            } else {
                log.error("response status error.status code:" + statusCode + ",url:" + url);
            }
        } catch (Exception e) {
            log.error("request error.request url:" + url, e);
        } finally {
            get.releaseConnection();
        }
        return body;
    }
}